package io.finer.erp.jeecg.stock.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.stock.dto.StkProcessingRecordDTO;
import io.finer.erp.jeecg.stock.entity.StkProcessingOrder;
import io.finer.erp.jeecg.stock.entity.StkProcessingRecord;
import io.finer.erp.jeecg.stock.service.IStkProcessingOrderService;
import io.finer.erp.jeecg.stock.service.IStkProcessingRecordService;
import io.finer.erp.jeecg.stock.vo.StkProcessingOrderPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

 /**
 * @Description: 代加工单
 * @Author: jeecg-boot
 * @Date:   2021-04-19
 * @Version: V1.0
 */
@Api(tags="代加工单")
@RestController
@RequestMapping("/stock/stkProcessingOrder")
@Slf4j
public class StkProcessingOrderController {
	@Autowired
	private IStkProcessingOrderService stkProcessingOrderService;
	@Autowired
	private IStkProcessingRecordService stkProcessingRecordService;
	@Autowired
	private IBasCustomerService customerService;
	
	/**
	 * 分页列表查询
	 *
	 * @param stkProcessingOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "代加工单-分页列表查询")
	@ApiOperation(value="代加工单-分页列表查询", notes="代加工单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(StkProcessingOrder stkProcessingOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<StkProcessingOrder> queryWrapper = QueryGenerator.initQueryWrapper(stkProcessingOrder, req.getParameterMap());
		Page<StkProcessingOrder> page = new Page<StkProcessingOrder>(pageNo, pageSize);
		IPage<StkProcessingOrder> pageList = stkProcessingOrderService.page(page, queryWrapper);
		System.out.println(JSONObject.toJSONString(pageList));
		List<StkProcessingOrder> list = pageList.getRecords();
		if(CollUtil.isNotEmpty(list)) {
			List<String> customerIds = Lists.newArrayList();
			for (StkProcessingOrder StkProcessingOrder : list) {
				String customerId = StkProcessingOrder.getCustomerId();
				if(StringUtils.isNotBlank(customerId)) {
					customerIds.add(customerId);
				}
			}
			if(CollUtil.isNotEmpty(customerIds)) {
				List<BasCustomer> customers = this.customerService.lambdaQuery().in(BasCustomer::getId, customerIds).list();
				if(CollUtil.isNotEmpty(customers)) {
					Map<String, BasCustomer> map = Maps.newLinkedHashMap();
					for (BasCustomer customer : customers) {
						map.put(customer.getId(), customer);
					}
					for (StkProcessingOrder order : list) {
						String customerId = order.getCustomerId();
						if(StringUtils.isNotBlank(customerId)) {
							BasCustomer customer = map.get(customerId);
							if(null == customer) {
								continue;
							}
							order.setCustomerName(customer.getName());
						}
					}
				}
			}
		}
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param stkProcessingOrderPage
	 * @return
	 */
	@AutoLog(value = "代加工单-添加")
	@ApiOperation(value="代加工单-添加", notes="代加工单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody StkProcessingOrderPage stkProcessingOrderPage) {
		StkProcessingOrder stkProcessingOrder = new StkProcessingOrder();
		BeanUtils.copyProperties(stkProcessingOrderPage, stkProcessingOrder);
		stkProcessingOrder.setOrderStatus("1");
		stkProcessingOrderService.saveMain(stkProcessingOrder, stkProcessingOrderPage.getStkProcessingRecordList());
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param stkProcessingOrderPage
	 * @return
	 */
	@AutoLog(value = "代加工单-编辑")
	@ApiOperation(value="代加工单-编辑", notes="代加工单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody StkProcessingOrderPage stkProcessingOrderPage) {
		StkProcessingOrder stkProcessingOrder = new StkProcessingOrder();
		BeanUtils.copyProperties(stkProcessingOrderPage, stkProcessingOrder);
		StkProcessingOrder stkProcessingOrderEntity = stkProcessingOrderService.getById(stkProcessingOrder.getId());
		if(stkProcessingOrderEntity==null) {
			return Result.error("未找到对应数据");
		}
		stkProcessingOrderService.updateMain(stkProcessingOrder, stkProcessingOrderPage.getStkProcessingRecordList());
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "代加工单-通过id删除")
	@ApiOperation(value="代加工单-通过id删除", notes="代加工单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		StkProcessingOrder processingOrder = this.stkProcessingOrderService.getById(id);
		if(null != processingOrder) {
			String orderStatus = processingOrder.getOrderStatus();
			if(StringUtils.isNotBlank(orderStatus) && !"1".equals(orderStatus)) {
				return Result.error("该代加工单已经开始生产，不能删除");
			}
		}
		stkProcessingOrderService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "代加工单-批量删除")
	@ApiOperation(value="代加工单-批量删除", notes="代加工单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		List<StkProcessingOrder> orderList = this.stkProcessingOrderService.listByIds(idList);
		if(CollUtil.isNotEmpty(orderList)) {
			for (StkProcessingOrder order : orderList) {
				String orderStatus = order.getOrderStatus();
				if(StringUtils.isNotBlank(orderStatus) && !"1".equals(orderStatus)) {
					return Result.error(new StringBuffer("代加工单").append(order.getOrderNo()).append("已经开始生产，不能删除").toString());
				}
			}
		}
		this.stkProcessingOrderService.delBatchMain(idList);
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "代加工单-通过id查询")
	@ApiOperation(value="代加工单-通过id查询", notes="代加工单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		StkProcessingOrder stkProcessingOrder = stkProcessingOrderService.getById(id);
		if(stkProcessingOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(stkProcessingOrder);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "代加工详细记录-通过主表ID查询")
	@ApiOperation(value="代加工详细记录-通过主表ID查询", notes="代加工详细记录-通过主表ID查询")
	@GetMapping(value = "/queryStkProcessingRecordByMainId")
	public Result<?> queryStkProcessingRecordListByMainId(@RequestParam(name="id",required=true) String id) {
		List<StkProcessingRecordDTO> stkProcessingRecordList = stkProcessingRecordService.selectDTOByMainId(id);
		IPage <StkProcessingRecordDTO> page = new Page<>();
		page.setRecords(stkProcessingRecordList);
		page.setTotal(stkProcessingRecordList.size());
		return Result.ok(page);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param stkProcessingOrder
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StkProcessingOrder stkProcessingOrder) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<StkProcessingOrder> queryWrapper = QueryGenerator.initQueryWrapper(stkProcessingOrder, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<StkProcessingOrder> queryList = stkProcessingOrderService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<StkProcessingOrder> stkProcessingOrderList = new ArrayList<StkProcessingOrder>();
      if(oConvertUtils.isEmpty(selections)) {
          stkProcessingOrderList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          stkProcessingOrderList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<StkProcessingOrderPage> pageList = new ArrayList<StkProcessingOrderPage>();
      for (StkProcessingOrder main : stkProcessingOrderList) {
          StkProcessingOrderPage vo = new StkProcessingOrderPage();
          BeanUtils.copyProperties(main, vo);
          List<StkProcessingRecord> stkProcessingRecordList = stkProcessingRecordService.selectByMainId(main.getId());
          vo.setStkProcessingRecordList(stkProcessingRecordList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "代加工单列表");
      mv.addObject(NormalExcelConstants.CLASS, StkProcessingOrderPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("代加工单数据", "导出人:"+sysUser.getRealname(), "代加工单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<StkProcessingOrderPage> list = ExcelImportUtil.importExcel(file.getInputStream(), StkProcessingOrderPage.class, params);
              for (StkProcessingOrderPage page : list) {
                  StkProcessingOrder po = new StkProcessingOrder();
                  BeanUtils.copyProperties(page, po);
                  stkProcessingOrderService.saveMain(po, page.getStkProcessingRecordList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }

}
